var express = require('express');
var router = express.Router();
var db = require('../mod/seq.js');
var err = require('../mod/err.js');
var crypto = require('crypto');
var auth = require('../mod/auth.js');
var config = require('../config');

/* GET users listing. */
router.get('/', function(req, res) {
  res.render('user', { title: '铁路沉降形变监测平台' });
});

//user status
router.get('/login', function(req, res){
  if(req.session && req.session.username){
    res.json({
      username: req.session.username,
      code: req.session.code,
      auth: req.session.auth
    });
  }else{
    res.json(err.not_login);
  }
});
//Create an user if there is none.
setTimeout(function () {
  db.user.count().then(function (count) {
    if(count!=0) return;
    db.user.create({
      username: 'admin',
      password: crypto.createHash('sha1').update('123456').digest('hex'),
      auth: 0
    })
  })
},1000);
//Create
router.post('/', function(req, res){
  var data = req.body;
  if(!data) {
    res.status(400).json(err.format_err);
  }else if(!data.username||!data.password){
    res.status(400).json(err.need_name_password);
  }else if(data.password&&data.password.length<6){
    res.status(400).json(err.password_six);
  }else{
    db.user.find({
      where: {
        username: data.username
      }
    }).then(function(msg){
      if(msg){
        res.status(400).json(err.user_exist);
      }else{
        db.user.create({
          username: data.username,
          password: crypto.createHash('sha1').update(data.password).digest('hex'),
          auth: data.auth
        }).then(function(msg){
          if(!msg) {
            res.json({});
            return;
          }
          auth.getAuth(msg.username);
          res.json({
            auth: msg.auth
          });
        });
      }
    });
  }
});

//Logout
router.get('/logout', function(req, res){
  req.session.destroy();
  res.json();
});

//User list
router.get('/list', function(req, res){
  var l = req.query.limit || 100;
  var p = req.query.offset || 0;
  db.user.findAndCount({
    limit: parseInt(l),
    offset: parseInt(p),
    attributes: ['username','auth']
  }).then(function(msg){
    res.json(msg);
  })
});

//all user
router.get('/all', function(req, res){
  var data = req.query;
  var obj = {
    attributes: ['username','auth']
  };
  if(data.auth){
    obj.where = {
      auth: data.auth*1
    }
  }
  db.user.findAll(obj).then(function(msg){
    res.json(msg);
  })
});

//One user's detail
router.get('/detail/:username', function(req, res){
  db.user.find({
    where : { username: req.params.username },
    attributes: ['username','auth','createdAt']
  }).then(function(msg){
    if(!msg||(msg.auth<=req.session.auth&&msg.username != req.session.username))
      res.status(401).json(err.no_auth);
    else res.json(msg);
  })
});

//edit an user
router.put('/:username',function(req, res){
  db.user.findOne({
    where : { username: req.params.username },
    attributes: ['username','auth','password']
  }).then(function(_user){
    if(!_user||(_user.dataValues.auth<=req.session.auth&&_user.username != req.session.username))
      res.status(401).json(err.no_auth);
    else {
      var data = req.body;
      if(!data) {
        res.status(400).json(err.format_err);
      }else {
        var obj = {};
        obj.auth = data.auth;
        if(data.password){
          var _old = crypto.createHash('sha1').update(data.password1).digest('hex');
          var _real = _user.dataValues.password;
          if(_old!=_real) {
            res.status(400).json(err.error_name_password);
            return;
          }
          obj.password = crypto.createHash('sha1').update(data.password).digest('hex');
        }
        db.user.update(obj,{
          where: {username: req.params.username}
        }).then(function(msg){
          if(msg[0] ==1){
            auth.getAuth(_user.username);
          }
          res.json(msg);
        })
      }
    }
  });

});

//delete an user
router.delete('/:username',function(req, res){
  db.user.find({
    where : { username: req.params.username },
    attributes: ['username','auth']
  }).then(function(_user){
    if(!_user||(_user.dataValues.auth<=req.session.auth&&_user.username != req.session.username))
      res.status(400).json(err.no_auth);
    else {
      db.user.destroy({
        where: {username: req.params.username},
        limit: 1
      }).then(function (msg) {
        if (msg == 1 || msg[0] ==1) {
          auth.deleteAuth(req.params.username);
          res.json(msg);
        } else {
          res.status(400).json(err.no_auth);
        }
      });
    }
  });
});

module.exports = router;